/*
 * 签到规则配置
 */
$(function(){

	//** 
    var Cchecked = $('#Js_choose_checked'),
    	demospan = $('#demospan'),
    	ignoreList = $('#js_ignore_list'),
    	Cbtn = $('#Js_choose_btn'),
        Ccont = $('#Js_choose_cont'),
        Cok = $('#Js_choose_ok'),
        _checkedDate =[];

    //**
    var demo ={
    	dayDate:[],
    	ignoreUsers:[],
        signLocations:[]
    };

     //**
    var days ={
    	"monday":'周一',
    	"tuesday":'周二',
    	'wednesday':'周三',
    	'thursday':'周四',
    	'friday':'周五',
    	'saturday':'周六',
    	'sunday':'周日',
    	'ignoreHoliday':'法定节假日除外'
    };



    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green'
    });

    $('#js_ignore_select').chosen({}).change(function(event){
        // console.log(event)
        // console.log($(event.currentTarget))
    });

    $('#js_ignore_select_chosen').hide();


    //**页面数据初始化
    jQuery.ajax({
    	url: '/sign/signRegulation.json',
		dataType: 'json',
		timeout: 1000,
		cache:false,
		error: function(date){
			swal({
                title: "获取失败!",
                text: "请检查您的网络!",
                type: "error"
            });
		},
		success: function(data){
			var Data = data['data'],
				_date = [];

			//** 初始化签到日期
	       if(Data['monday']){
	       		_date.push(days['monday']);
	       		demo.dayDate.push('monday');
	       }
	       if(Data['tuesday']){
	       		_date.push(days['tuesday']);
	       		demo.dayDate.push('tuesday');
	       }
	       if(Data['wednesday']){
	       		_date.push(days['wednesday']);
	       		demo.dayDate.push('wednesday');
	       }
	       if(Data['thursday']){
	       		_date.push(days['thursday']);
	       		demo.dayDate.push('thursday');
	       }
	       if(Data['friday']){
	       		_date.push(days['friday']);
	       		demo.dayDate.push('friday');
	       }
	       if(Data['saturday']){
	       		_date.push(days['saturday']);
	       		demo.dayDate.push('saturday');
	       }
	       if(Data['sunday']){
	       		_date.push(days['sunday']);
	       		demo.dayDate.push('sunday');
	       }
	       if(Data['ignoreHoliday']){
	       		_date.push(days['ignoreHoliday']);
	       		demo.dayDate.push('ignoreHoliday');
	       }

	       Cchecked.append(_date.join('，'));

	      //** 初始化推送时间
	      demospan.text(Data['pushTime']);

	      //**初始化不需要签到人员名单
	      jQuery.each(Data['ignoreUsers'], function(i, n){
	      	 	ignoreList.append('<a id="'+ n['userId'] +'" class="del" href="javascript:void(0)">'+ n['userName'] +'<i class="fa fa-minus-circle"></i></a>')
	      	 	demo.ignoreUsers.push(n['userId']);
	      });

          //**初始化签到地点
          jQuery.each(Data['signLocations'], function(m, k){

            demo.signLocations.push(k);

            var _addHtml = '<div class="clearfix js_choose_map_subcont">'+
                                '<div class="form-group">'+
                                    '<label class="col-sm-5 control-label map-site"><i class="fa fa-map-marker"></i>&nbsp;&nbsp;'+ k['location'] +'（'+ k['lat'] +','+ k['lng'] +'）</label>'+
                                    '<div class="col-sm-3">'+
                                        '<div class="input-group">'+
                                            '<span class="input-group-addon">方圆</span>'+
                                            '<input type="text" required digits="true" class="form-control" value="'+ k['rang'] +'" name="mapsite'+ parseInt(k['lat']) +  parseInt(k['lng']) + m +'">'+
                                            '<span class="input-group-addon">m有效</span>'+
                                        '</div>'+
                                    '</div>'+
                                    '<div class="col-sm-1 col-sm-offset-1">'+
                                       '<a href="JavaScript:void(0)" maplat="'+ k['lat'] +'" class="btn btn-primary btn-sm js_del_map_coords">删除</a>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="hr-line-dashed"></div>'+
                            '</div>';


            $('#Js_choose_map_subcont').append(_addHtml);

          });

		}
    });


    //**显示隐藏
    Cbtn.on('click',function(){
        var _has = $(this).hasClass('open');
        if(_has){
            Ccont.hide();
            $(this).removeClass('open');
        }else{
            Ccont.slideDown(180);
            $(this).addClass('open');
        }
    });

    //选中**
    Ccont.on('ifChecked', '.i-checks', function(event){
        var _val = $(this).val();
        _checkedDate.push(_val);

    });

    //**取消
    Ccont.on('ifUnchecked', '.i-checks', function(event){
        var _val = $(this).val();

        jQuery.each(_checkedDate, function(i, n){
            if(n == _val){
                _checkedDate.splice(i,1);
                return false;
            }
        })

    });

    //**确定
    Cok.on('click', function(){
        var _date =[],  	//计算 工作日
            _nmber = 0,		//计算 工作日
            addHtml = '';   //插入文本

        Ccont.hide();
        Cbtn.removeClass('open');
        Cchecked.html('');
        demo.dayDate=[];

        jQuery.each(_checkedDate, function(i, n){
            demo.dayDate.push(n);
            _checkedDate.splice(i,1,days[n]);
        });

        addHtml = _checkedDate.join('，');
        Cchecked.append(addHtml);

        $('.i-checks').iCheck('uncheck');
        _checkedDate =[];
    });

	<!-- // ---------------------------------------------------------------  -->

	//**不需要签到人员名单 提交数据
    //**select下拉事件
    $('#js_ignore_select').change(function(){

        var _this = $(this),
        	_has = false,
            _id = _this.attr('id'),
            _userId = _this.val(),
            _userText = $('#'+ _id +'_chosen').find('span').text();
        
        if(!_userId){
        	return false ;
        }

        //**遍历排除已经相同项
        jQuery.each(demo.ignoreUsers, function(i, n){
      	 	if(n == _userId){
      	 		_has = true;
      	 		return false;
      	 	}
      	});

      	if(!_has){
      		//push 员工id
        	demo.ignoreUsers.push(_userId);

        	ignoreList.append('<a id="'+ _userId +'" class="del" href="javascript:void(0)">'+ _userText +'<i class="fa fa-minus-circle"></i></a>');
      	}

        $('#js_ignore_cont').find('.addbtn').show();
        $('#js_ignore_select_chosen').hide();

    });
    //**删除不需要签到人员名单
    ignoreList.on('click', '.del', function(){
         var _id = Number($(this).attr('id'));
         $(this).remove();
         demo.ignoreUsers.splice(jQuery.inArray(_id, demo.ignoreUsers),1);
    });

    //**添加不需要签到人员名单
    $('#js_ignore_cont').on('click', '.addbtn', function(){
        $('#js_ignore_select_chosen').show();
        $(this).hide();
    });
    <!-- // ---------------------------------------------------------------  -->

    //**弹窗回调事件
    $('#js_map').on('show.bs.modal', function (event) {

    })

    //**关闭弹窗触发事件
    $('#js_map_submit').on('click', function(){
        $('#js_map').modal('hide');

        var location = "",
            time = '';

        if(province){
            location += province ;
        }
        if(city){
            location += city ;
        }
        if(district){
            location += district ;
        }
        if(street){
            location += street ;
        }
        if(streetNumber){
            location += streetNumber ;
        }

        var  map = {
            "lat": lat,
            "lng": lng,
            "location": location,
            "rang": 1000
        };

        var myDate = new Date();
            time = myDate.getMinutes().toString() + myDate.getSeconds().toString() + myDate.getMilliseconds().toString();

        var _addHtml = '<div class="clearfix js_choose_map_subcont">'+
                            '<div class="form-group">'+
                                '<label class="col-sm-5 control-label map-site"><i class="fa fa-map-marker"></i>&nbsp;&nbsp;'+ location +'（'+ lat +','+ lng +'）</label>'+
                                '<div class="col-sm-3">'+
                                    '<div class="input-group">'+
                                        '<span class="input-group-addon">方圆</span>'+
                                        '<input type="text" required digits="true" class="form-control" value="1000" name="mapsite'+ time + '">'+
                                        '<span class="input-group-addon">m有效</span>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="col-sm-1 col-sm-offset-1">'+
                                   '<a href="JavaScript:void(0)" maplat="'+ lat +'" class="btn btn-primary btn-sm js_del_map_coords">删除</a>'+
                                '</div>'+
                            '</div>'+
                            '<div class="hr-line-dashed"></div>'+
                        '</div>';


        $('#Js_choose_map_subcont').append(_addHtml);

        demo.signLocations.push(map);
    })

    //**删除坐标
    $('#Js_choose_map_subcont').on('click', '.js_del_map_coords', function(){
        var _maplat = $(this).attr('maplat'),
            mapcont = $(this).parents('.js_choose_map_subcont');

        //**遍历
        jQuery.each(demo.signLocations, function(i, n){
            if(n['lat'] == _maplat){
               demo.signLocations.splice(i,1);
               return false;
            }
        });
        mapcont.remove();
    });

    <!-- // ---------------------------------------------------------------  -->

    //** 插件初始化提交表单
    $("#Js_annual").validate({
    	submitHandler:function(form){

    		if(!demo.dayDate.length){
	            swal({
	                title: "提交失败!",
	                text: "签到日期为空!", //失败信息反馈
	                type: "error"
	            });

	            return false;
    		}

    		if(demospan.text() == ''){
	            swal({
	                title: "提交失败!",
	                text: "推送时间为空!", //失败信息反馈
	                type: "error"
	            });

	            return false;
    		}
    		
    		 if(!demo.signLocations.length){
                 swal({
                     title: "提交失败!",
                     text: "签到地址为空!", //失败信息反馈
                     type: "error"
                 });
                 return false;
             }
    		 
    		  var mapRang = $('#Js_choose_map_subcont').find('input'),
              number = mapRang.length,
              rang = [];

	          for (var i = 0; i < number; i++) {
	              rang.push(mapRang.eq(i).val());
	          };
	
	          //**
	         jQuery.each(rang, function(i, n){
	             demo.signLocations[i]['rang'] = Number(n);
	         });
	         
	        console.log(JSON.stringify(demo.signLocations))
	          
    		jQuery.post( ctx + '/sign/setRegulation.json',{
                dayDate: demo.dayDate,
                pushTime: demospan.text(),
                ignoreUsers:demo.ignoreUsers,
                signLocations:JSON.stringify(demo.signLocations) 
            }, function(data){
                // 成功
                if (data != null && data.code === "1") {
               	 swal({
                        title: "保存成功!",
                        type: "success"
                    });
                }
                else if(data != null && data.code === "403"){
                	swal({
                        title: "您未登录或登录信息已失效，请重新登录!", 
                        type: "error"
                    });
                }
                // 失败
                else{
                    swal({
                        title: "提交失败!",
                        type: "error"
                    });
                }
            }, 'json');

        },
        errorPlacement: function(error, element) {
            error.appendTo(element.parent().parent());
        }
    });

});